package edu.buffalo.cse.cse486_586.simpledht.bean;

import java.math.BigInteger;

import edu.buffalo.cse.cse486_586.simpledht.config.Configuration;
import edu.buffalo.cse.cse486_586.simpledht.config.Node;
import edu.buffalo.cse.cse486_586.simpledht.entity.KeyValuePair;
import edu.buffalo.cse.cse486_586.simpledht.entity.MyPackage;
import edu.buffalo.cse.cse486_586.simpledht.service.SendingThread;
import edu.buffalo.cse.cse486_586.util.AppUtil;
import edu.buffalo.cse.cse486_586.util.CommonUtil;

public class DHTBean {
	// private static final String TAG = "MessageBean";

	/*
	 * -1 < 1 > 0 ==
	 */
	public boolean isInrange(String key) {
		Node node = Configuration.getInstance().getNode();

		if (node.getSuccessor() == AppUtil.NONE_NODE
				|| node.getPredecessor() == AppUtil.NONE_NODE) {
			return true;
		}

		// convert the sha-1 string into big interger
		String hashKey = CommonUtil.genHash(key);
		String local = CommonUtil.genHash(String.valueOf(node.getNodePort()));
		String predecessor = CommonUtil.genHash(String.valueOf(node
				.getPredecessor()));

		BigInteger insertedKey = new BigInteger(hashKey, 16);
		BigInteger predecessorNode = new BigInteger(predecessor, 16);
		BigInteger localNode = new BigInteger(local, 16);
		// compare

		if (localNode.compareTo(predecessorNode) == -1) {
			BigInteger s = new BigInteger(
					"00000000000000000000000000000000000000000", 16);

			if (insertedKey.compareTo(predecessorNode) == 1
					|| (insertedKey.compareTo(localNode) == -1 && insertedKey
							.compareTo(s) == 1)) {
				return true;
			} else {
				return false;
			}
		}

		if (insertedKey.compareTo(localNode) == -1
				&& insertedKey.compareTo(predecessorNode) == 1) {
			return true;
		} else {
			return false;
		}
	}

	public void passKeyValePair(KeyValuePair kv) {
		MyPackage pkg = genInsertPkg(kv);
		int successorRedir = CommonUtil.getRedirectPort(Configuration
				.getInstance().getNode().getSuccessor());
		Thread t = new Thread(new SendingThread(AppUtil.EMULATOR_IP,
				successorRedir, pkg.toString()));
		t.start();
	}

	public MyPackage genInsertPkg(KeyValuePair kv) {
		return new MyPackage(AppUtil.PACKAGE_INSERT, kv.toString());
	}
}
